package com.qiu.aiteacherbacker.exception;

import com.qiu.aiteacherbacker.common.BaseResponse;
import com.qiu.aiteacherbacker.common.ErrorCode;
import com.qiu.aiteacherbacker.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLException;


/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(RuntimeException.class)
    public BaseResponse runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException:", e.getMessage(), e);
        // 数据库连接失败
        if (e.getMessage().contains("sql")) {
            return ResultUtils.error(ErrorCode.PARAM_ERROR, "数据库连接失败", "数据库配置有问题");
        }
        // 获取全部问题时
        if (e.getMessage().contains("userId")) {
            return ResultUtils.error(ErrorCode.SYS_ERROR, "userId为空", "userId是必填的");
        }

        return ResultUtils.error(ErrorCode.SYS_ERROR, e.getMessage(), "系统异常");
    }


    @ExceptionHandler(BusinessException.class)
    public BaseResponse BusinessExceptionHandler(BusinessException e) {
        log.error("BusinessException:", e);
        return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler(IOException.class)
    public BaseResponse IOExceptionHandler(IOException e) {
        log.error("IOException:", e.getMessage(), e);
        return ResultUtils.error(ErrorCode.SYS_ERROR, e.getMessage(), "IO流异常");
    }

    @ExceptionHandler(SQLException.class)
    public BaseResponse SQLExceptionHandler(SQLException e) {
        log.error("SQLException:", e);
        return ResultUtils.error(ErrorCode.SQL_ERROR, e.getMessage(), "数据库连接失败");
    }



    @ExceptionHandler(Exception.class)
    public BaseResponse ExceptionHandler(Exception e) {
        log.error("Exception:", e.getMessage(), e);
        return ResultUtils.error(ErrorCode.SYS_ERROR, e.getMessage(), "未知");
    }

}
